import axios from "@/js_sdk/gangdiedao-uni-axios";
import {encrypt, decrypt} from './cbcbase'

const DEDUG = 1;
let host = "";

// 开发环境
if (process.env.NODE_ENV === "development") {
	// 开发环境下使用域名
	switch (DEDUG) {
	case 1:
		host = "http://111.62.218.228:18081/smp";
		break; // 测试环境
	case 2:
		host = "http://localhost/fkySrv/public/";
		break; // 本地环境
	}
} else { // 生产环境
	host = "http://111.62.218.228:18081/smp";
}


// 创建自定义接口服务实例
const http = axios.create({
	// baseURL: [baseURL],
	timeout: 6000, // 不可超过 manifest.json 中配置 networkTimeout的超时时间
	// #ifdef H5
	withCredentials: true,
	// #endif
	headers: {
		"Content-Type": "application/json"
		// 'X-Requested-With': 'XMLHttpRequest',
	},
});

// 拦截器 在请求之前拦截
http.interceptors.request.use(req => {
	req.url = host + req.url
	const token =  uni.getStorageSync('token');
	// console.log(token)
	if (token) req.headers["X-Access-Token"] = token
	// if(!token) {
	// 	uni.redirectTo({
	// 		url:'/pages/register/login.vue'
	// 	})
	// 	return
	// }
	 if (req.host_flag) {
		 
		 if (req.method === 'get') {
			 // @ts-ignore
			 let data = encodeURIComponent(encrypt(req.params))
			 req.params = {};
			 req.params.data = data
			 
			 console.log(req)
		 } else {
			 req.data = {data: encrypt(req.data)}
			 // console.log(decrypt(req.data.data))
		 }
	 }
	console.log(req)
	return req
})

// 拦截器 在请求之后拦截
http.interceptors.response.use(res => {
	uni.hideLoading();
	// console.log(res.headers.encry)
	// console.log(res)
	if(res.headers.encry){
		res.data = decrypt(res.data)
		try {
		res.data = JSON.parse(res.data)
		} catch (err) {
			console.log("格式化解密数据失败")
		}
	}
	return res
}, error => {
	// 请求出错，根据返回状态码判断出错原因
	console.log(JSON.stringify(error));
	uni.hideLoading();
	if (error) {
		console.log('error',error)
		
		return "请求失败"
	}
	
});

export default http;
